//
//  SEGIAnalyticsPageDBManager.m
//  test
//
//  Created by 刘山 on 2017/12/3.
//  Copyright © 2017年 刘山. All rights reserved.
//

#import "SEGIAnalyticsPageDBManager.h"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

//  页面统计 数据库名
static NSString* SEGIAnalyticsPageDBName = @"SEGPageDB";
//  页面统计 表名
static NSString* SEGIAnalyticsPageTableName = @"SEGPageTable";

//  字段
static NSString* varPageName = @"pageName";
static NSString* varStartTimeStamp = @"startTimeStamp";

@implementation SEGIAnalyticsPageModel
@end

@implementation SEGIAnalyticsPageDBManager
/**
 * 创建页面统计数据表
 * @author Sam
 */
+(void)segPageCreateTable{

    if ([self isTableOK:SEGIAnalyticsPageTableName DB:SEGIAnalyticsPageDBName]) {
        return;
    }
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ TEXT , %@ TEXT);",SEGIAnalyticsPageTableName,varPageName,varStartTimeStamp];    
    [self segCreateTableWithDBName:SEGIAnalyticsPageDBName WithTable:sql];
}

/**
 * 把进入到页面的相关数据保存到本地数据库中
 * @author Sam
 * @param pageName  页面名称
 * @param startTimeStamp  开始时间
 */
+(BOOL)segPageInsertWithPageName:(NSString*)pageName startTime:(NSString*)startTimeStamp{
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    
    pageName = (pageName && [pageName isKindOfClass:[NSString class]]) ? pageName : @"";
    [data setObject:pageName forKey:varPageName];
    
    startTimeStamp = (startTimeStamp && [startTimeStamp isKindOfClass:[NSString class]]) ? startTimeStamp : @"0";
    [data setObject:startTimeStamp forKey:varStartTimeStamp];
  
    return [self segInsertWithDictionary:data DBName:SEGIAnalyticsPageDBName WithTable:SEGIAnalyticsPageTableName];
}

/**
 * 所有数据库中页面的数据
 * @author Sam
 * @param pageName  页面名称
 * 逻辑：
 *    1. 从数据库中获取 进入界面记录的数据
 *    2. 删除数据库中的获取出来的数据
 */
+(SEGIAnalyticsPageModel*)segPageQuryWithPageName:(NSString*)pageName{
    
    pageName = (pageName && [pageName isKindOfClass:[NSString class]]) ? pageName : @"";
    
    NSString *querySql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?;",SEGIAnalyticsPageTableName,varPageName];
    
    NSArray *data = [self segExecuteQueryWithDBName:SEGIAnalyticsPageDBName WithSQL:querySql OfValues:@[pageName]];
    
    if (data && data.count > 0) {
        
        NSString *delSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?;",SEGIAnalyticsPageTableName,varPageName];
    
        [self segExecuteDB:SEGIAnalyticsPageDBName WithSQL:delSql OfValues:@[pageName]];
        
        NSDictionary *json = data.firstObject;        
        return [SEGIAnalyticsPageModel yy_modelWithJSON:json];
    }
    
    return nil;
}

@end
